package com.ba.grain;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Node;

import util.FoodType;
import util.Grade;
import util.RequestResponse;
import util.Site;
import util.XMLParser;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class LocalRecordActivity extends ListActivity implements OnClickListener,
		OnItemSelectedListener {

	private static final String ROOT = "Grain";
	protected static final int REQUEST_COLLECT = 0x1000;
	private String NAME_RECORDS = "records";

	public static final String KEY_DISPLAY = "key_display";
	public static final String KEY_ITEM_DISPLAYED = "key_item";
	private EditText mBuyPrice, mTradePrice, mDayRetailPrice, mWeekRetailPrice;
	private TextView mCollector, mCompany;
	private Spinner mFoodType, mGrade, mCollectionStation;
	private ListItem mItemAttached;
	private Button mButtonSave, mButtonReport, mButtonPicReport, mButtonBack2List, mGroupReport;
	private View mAddAndExport;
	private ProgressDialog mDialog;
	public ActionMode mActionMode;
	private OnItemLongClickListener mOnItemLongClickListener;
	private File mFileUpload;

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		NAME_RECORDS = G.sUser.loginName;
		setContentView(R.layout.record_list);
		initViews();
		// android:choiceMode="multipleChoiceModal"
		getListView().setChoiceMode(
				VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB ? ListView.CHOICE_MODE_MULTIPLE_MODAL
						: ListView.CHOICE_MODE_NONE);
		DataUploadAdapter dua = new DataUploadAdapter(this);
		addLocalRecords(dua);
		View header = LayoutInflater.from(this).inflate(R.layout.list_head, getListView(), false);
		mAddAndExport = header.findViewById(R.id.operations);
		mGroupReport = (Button) header.findViewById(R.id.btn_upload);
		header.findViewById(R.id.btn_collect).setOnClickListener(this);
		header.findViewById(R.id.btn_upload).setOnClickListener(this);
		header.findViewById(R.id.btn_export).setOnClickListener(this);
		getListView().addHeaderView(header);
		setListAdapter(dua);
		if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
			getListView().setMultiChoiceModeListener(new MultiChoiceModeListener());
		} else {
			mOnItemLongClickListener = new AbsListView.OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
						long id) {
					getListView().setOnLongClickListener(null);
					mAddAndExport.setVisibility(View.GONE);
					mGroupReport.setVisibility(View.VISIBLE);
					getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
					return false;
				}
			};
			getListView().setOnItemLongClickListener(mOnItemLongClickListener);
		}
		mDialog = new ProgressDialog(this);
		mDialog.setCancelable(false);
		mDialog.setMessage("上报中。。");

		PackageManager manager = getPackageManager();
		try {
			PackageInfo pi = manager.getPackageInfo(getPackageName(), 0);
			int versionCode = pi.versionCode;
			if (pi.versionName.compareTo(G.sNewVersionApk.mVersion) < 0) {
				showUpdateDlg();
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}

	private void showUpdateDlg() {
		String msg = String.format("版本:%s。\n更新日志：%s。", G.sNewVersionApk.mVersion,
				G.sNewVersionApk.mChangeLog);
		new AlertDialog.Builder(this).setMessage(msg).setTitle("发现新版本")
				.setPositiveButton("升级", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						mDialog.setMessage("下载中...");
						File dir = makeRootDir();
						final File newApkPath = new File(dir, String.format("%s.apk",
								G.sNewVersionApk.mVersion));
						doDownLoadNewVersion(G.sNewVersionApk.mPath, newApkPath.getPath(),
								new Runnable() {

									@Override
									public void run() {
										mDialog.dismiss();
										Intent intent = new Intent(Intent.ACTION_VIEW);
										intent.setDataAndType(Uri.fromFile(newApkPath),
												"application/vnd.android.package-archive");
										startActivity(intent);
									}
								});
					}
				}).setNegativeButton("取消", null).show();
	}

	protected void doDownLoadNewVersion(final String remoteFilePath, final String localPath, Runnable callback) {
		mDialog.show();
		new Thread() {
			@Override
			public void run() {
				super.run();
				int result = RequestResponse.downLoadNewFile(G.sSocket, remoteFilePath, localPath);
			}

		}.start();
	}

	@Override
	public void onBackPressed() {
		if (getListView().getVisibility() == View.VISIBLE) {
			new AlertDialog.Builder(this).setMessage("确定退出程序吗？").setTitle(R.string.app_name)
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
							try {
								G.sSocket.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}).setNegativeButton("取消", null).show();
			return;
		} else {
			getListView().setVisibility(View.VISIBLE);
		}
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_collect) {
			getListView().setVisibility(View.GONE);
			mItemAttached = new ListItem();
			View bts = findViewById(R.id.btns);
			bts.setVisibility(View.VISIBLE);
			CollectActivity.clear(mBuyPrice, mTradePrice, mDayRetailPrice, mWeekRetailPrice);
		} else if (R.id.btn_upload == v.getId()) {
			SparseBooleanArray sba = getListView().getCheckedItemPositions();
			List<ListItem> items = new ArrayList<ListItem>();
			for (int i = 0; i < sba.size(); i++) {
				int key = sba.keyAt(i);
				if (sba.get(key)) {
					ListItem li = (ListItem) getListView().getItemAtPosition(key);
					if (li.isUploaded()) {
						continue;
					}
					items.add(li);
				}
			}

			ListItem[] arr = new ListItem[items.size()];
			for (int i = 0; i < arr.length; i++) {
				arr[i] = items.get(i);
			}
			if (arr.length == 0) {
				Toast.makeText(this, "没有需要上报的数据", Toast.LENGTH_SHORT).show();
				if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
					mActionMode.finish();
				} else {
					clearListChoice();
				}
				return;
			}
			// getListView().clearChoices();
			doReport(null, null, arr);
		} else if (v.getId() == R.id.btn_export) {
			File dir = makeRootDir();
			File file = new File(dir, String.format("%s.xml", G.sUser.loginName));
			try {

				file.createNewFile();
				XMLParser parser = new XMLParser();
				parser.setEncoder(XMLParser.UTF_8);
				// resp[0] = parser.addTag(REQ, NAME, CHECK_USER, PARAM, userID,
				// PASSWORD, pwd);
				Node root = parser.addTag("Records", "LoginName", G.sUser.loginName, "CNName",
						G.sUser.cnName);
				SharedPreferences sp = getSharedPreferences(NAME_RECORDS, MODE_PRIVATE);
				Map<String, ?> map = sp.getAll();
				for (String key : map.keySet()) {
					Object value = map.get(key);
					parser.add_tag_parent(root, "Record", "Value", value.toString());
				}
				RequestResponse.save2File(parser.toString(), file.getPath(), false);
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
				return;
			}
			Toast.makeText(this, String.format("记录已成功导出至%s", file.getPath()), Toast.LENGTH_LONG)
					.show();
		} else if (v == mButtonReport) {
			if (!initItem(mItemAttached)) {
				return;
			}
			doReport(null, null, mItemAttached);
		} else if (v == mButtonSave) {
			if (!initItem(mItemAttached)) {
				return;
			}
			doSave(mItemAttached);
			getListView().setVisibility(View.VISIBLE);
		} else if (v == mButtonBack2List) {
			getListView().setVisibility(View.VISIBLE);
		} else if (mButtonPicReport == v) {
			if (!initItem(mItemAttached)) {
				return;
			}
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			File dir = makeRootDir();
			String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(System
					.currentTimeMillis()));
			name = String.format("%s_%s", NAME_RECORDS, name);
			try {
				mFileUpload = File.createTempFile(name, ".jpg", dir);
				Uri uri = Uri.fromFile(mFileUpload);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
				intent.putExtra("NAME", name);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
				startActivityForResult(intent, 1);
			} catch (IOException e) {
				e.printStackTrace();
				Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
				return;
			}

		}
	}

	private File makeRootDir() {
		File dir = new File(Environment.getExternalStorageDirectory(), ROOT);
		dir.mkdirs();// 创建文件夹
		return dir;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			try {
				InputStream is = new FileInputStream(mFileUpload);
				doReport(mFileUpload.getName(), is, mItemAttached);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		if (ListView.CHOICE_MODE_MULTIPLE == l.getChoiceMode()) {
			return;
		}
		if (position == 0) {
			return;
		}
		View bts = findViewById(R.id.btns);
		bts.setVisibility(View.GONE);
		ListItem item = (ListItem) getListAdapter().getItem(position - 1);
		mBuyPrice.setText(String.valueOf(item.buyPrice));
		mTradePrice.setText(String.valueOf(item.tradePrice));
		mDayRetailPrice.setText(String.valueOf(item.dayRetailPrice));
		mWeekRetailPrice.setText(String.valueOf(item.weekRetailPrice));
		// mType.s(Integer.parseInt(item.mType));
		// mGrade.setSelection(Integer.parseInt(item.mLevel));
		getListView().setVisibility(View.GONE);
	}

	@SuppressLint("NewApi")
	private void onReport(int result, String detail, ListItem[] items) {
		mDialog.dismiss();
		if (result == 0) {
			for (int i = 0; i < items.length; i++) {
				items[i].mUploaded = true;
			}
			if (getListView().getVisibility() == View.VISIBLE) {// 列表上报
				mAddAndExport.setVisibility(View.VISIBLE);
				mGroupReport.setVisibility(View.GONE);
				if (mActionMode != null) {
					mActionMode.finish();
				} else {
					clearListChoice();
				}
			} else {
				getListView().setVisibility(View.VISIBLE);
			}
			DataUploadAdapter dau = (DataUploadAdapter) getListAdapter();
			dau.notifyDataSetChanged();
			Toast.makeText(this, String.format("成功上报了%d项记录", items.length), Toast.LENGTH_SHORT)
					.show();
		} else {
			Toast.makeText(this, String.format("%s(%s)", "上传未成功", detail), Toast.LENGTH_SHORT)
					.show();
		}
		doSave(items);
	}

	private void clearListChoice() {
		mAddAndExport.setVisibility(View.VISIBLE);
		mGroupReport.setVisibility(View.GONE);
		getListView().setOnItemLongClickListener(mOnItemLongClickListener);
		getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
		getListView().clearChoices();
		for (int i = 0; i < getListView().getChildCount(); i++) {
			View c = getListView().getChildAt(i);
			if (c instanceof Checkable) {
				((Checkable) c).setChecked(false);
			}
		}
	}

	private void doReport(final String fileName, final InputStream is, final ListItem... items) {
		mDialog.setMessage("上报中...");
		mDialog.show();
		new Thread() {

			@Override
			public void run() {
				super.run();
				int serinum = (int) System.currentTimeMillis();
				String[] attr = new String[] { "site_id", "serinum", "foodType_id", "grade_id",
						"buyPrice", "tradePrice", "dayRetailPrice", "weekRetailPrice" };
				String[][] values = new String[items.length][attr.length];
				for (int i = 0; i < items.length; i++) {
					values[i][0] = String.valueOf(items[i].site_id);
					values[i][1] = String.valueOf(serinum);
					values[i][2] = String.valueOf(items[i].foodType_id);
					values[i][3] = String.valueOf(items[i].grade_id);
					values[i][4] = String.valueOf(items[i].buyPrice);
					values[i][5] = String.valueOf(items[i].tradePrice);
					values[i][6] = String.valueOf(items[i].dayRetailPrice);
					values[i][7] = String.valueOf(items[i].weekRetailPrice);
				}
				final Node[] node = new Node[1];
				final int result = RequestResponse.excuteInsert(G.sSocket, "tail_quotation", attr,
						values, fileName, is, serinum, node);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						String detail = null;
						if (result != 0) {
							detail = XMLParser.getAttrVal(node[0], RequestResponse.PARAM, "");
						}
						onReport(result, detail, items);
					}
				});
			}

		}.start();
	}

	private void doSave(ListItem... items) {
		SharedPreferences sp = getSharedPreferences(NAME_RECORDS, MODE_PRIVATE);
		Editor editor = sp.edit();
		DataUploadAdapter dua = (DataUploadAdapter) getListAdapter();
		for (int i = 0; i < items.length; i++) {
			// 如果在列表中上报，那么算作更新，否则为增加
			if (items[i].key == null) {
				items[i].key = String.valueOf(System.currentTimeMillis());
				dua.add(items[i]);
			}
			editor.putString(items[i].key, items[i].toString());
		}
		dua.notifyDataSetChanged();
		editor.commit();
		mTradePrice.requestFocus();
	}

	@Override
	public void setListAdapter(ListAdapter adapter) {
		super.setListAdapter(adapter);
	}

	private void addLocalRecords(DataUploadAdapter dua) {
		SharedPreferences sp = getSharedPreferences(NAME_RECORDS, MODE_PRIVATE);
		Map<String, ?> map = sp.getAll();
		for (String key : map.keySet()) {
			Object value = map.get(key);
			ListItem li = ListItem.fromString(value.toString());
			li.key = key;
			dua.add(li);
		}
	}

	private void initViews() {
		mCompany = (TextView) findViewById(R.id.company);
		mCompany.setText(String.valueOf(G.sUser.department_id));
		mBuyPrice = (EditText) findViewById(R.id.buy_price);
		mTradePrice = (EditText) findViewById(R.id.trade_price);
		mDayRetailPrice = (EditText) findViewById(R.id.day_retail_price);
		mWeekRetailPrice = (EditText) findViewById(R.id.week_retail_price);
		mCollectionStation = (Spinner) findViewById(R.id.sp_collection_station);
		ArrayAdapter<?> adapter = new ArrayAdapter<Site>(this,
				android.R.layout.simple_spinner_item, G.sSites);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mCollectionStation.setAdapter(adapter);
		mCollectionStation.setOnItemSelectedListener(this);

		mCollector = (TextView) findViewById(R.id.collector);
		mFoodType = (Spinner) findViewById(R.id.sp_type);
		mFoodType.setOnItemSelectedListener(this);
		onItemSelected(mCollectionStation, null, 0, 0);

		mGrade = (Spinner) findViewById(R.id.sp_level);
		onItemSelected(mFoodType, null, 0, 0);
		mCollector.setText(PreferenceManager.getDefaultSharedPreferences(this).getString(
				LoginActivity.KEY_COLLECTOR, null));

		mButtonSave = (Button) findViewById(R.id.save);
		mButtonReport = (Button) findViewById(R.id.report);
		mButtonPicReport = (Button) findViewById(R.id.pic_report);
		mButtonBack2List = (Button) findViewById(R.id.back2list);
		mButtonSave.setOnClickListener(this);
		mButtonPicReport.setOnClickListener(this);
		mButtonReport.setOnClickListener(this);
		mButtonBack2List.setOnClickListener(this);
	}

	private boolean initItem(ListItem item) {

		boolean legal = checkLegal(mBuyPrice, mTradePrice, mDayRetailPrice, mWeekRetailPrice);
		if (!legal) {
			return false;
		}
		if (legal) {
			try {
				item.buyPrice = Float.parseFloat(mBuyPrice.getText().toString());
			} catch (Exception e) {
				mBuyPrice.setError("请输入合法价格");
				mBuyPrice.requestFocus();
				return false;
			}
			try {
				item.tradePrice = Float.parseFloat(mTradePrice.getText().toString());
			} catch (Exception e) {
				mTradePrice.setError("请输入合法价格");
				mTradePrice.requestFocus();
				return false;
			}
			try {
				item.dayRetailPrice = Float.parseFloat(mDayRetailPrice.getText().toString());
			} catch (Exception e) {
				mDayRetailPrice.setError("请输入合法价格");
				mDayRetailPrice.requestFocus();
				return false;
			}
			try {
				item.weekRetailPrice = Float.parseFloat(mWeekRetailPrice.getText().toString());
			} catch (Exception e) {
				mWeekRetailPrice.setError("请输入合法价格");
				mWeekRetailPrice.requestFocus();
				return false;
			}
		}
		Site site = (Site) mCollectionStation.getSelectedItem();
		item.site_id = site.id;
		item.mSite = site;
		FoodType ft = (FoodType) mFoodType.getSelectedItem();
		item.foodType_id = ft.id;
		item.mFoodType = ft;
		Grade gd = (Grade) mGrade.getSelectedItem();
		item.grade_id = gd.id;
		item.mGrade = gd;
		return true;
	}

	private boolean checkLegal(EditText... views) {
		for (int i = 0; i < views.length; i++) {
			EditText view = views[i];
			if (TextUtils.isEmpty(view.getText().toString())) {
				view.setError("请输入完整信息");
				view.requestFocus();
				return false;
			}
		}
		return true;
	}

	

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		if (parent == mCollectionStation) {
			Site site = (Site) mCollectionStation.getSelectedItem();
			if (site == null) {
				onNothingSelected(parent);
				return;
			}
			ArrayAdapter<FoodType> adapter = new ArrayAdapter<FoodType>(this,
					android.R.layout.simple_spinner_item, site.foods);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mFoodType.setAdapter(adapter);
		} else if (mFoodType == parent) {
			FoodType type = (FoodType) mFoodType.getSelectedItem();
			if (type == null) {
				onNothingSelected(parent);
				return;
			}
			ArrayAdapter<Grade> adapter = new ArrayAdapter<Grade>(this,
					android.R.layout.simple_spinner_item, type.grades);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mGrade.setAdapter(adapter);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		if (parent == mCollectionStation) {
			ArrayAdapter<FoodType> adapter = new ArrayAdapter<FoodType>(this,
					android.R.layout.simple_spinner_item, new FoodType[0]);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mFoodType.setAdapter(adapter);
		} else if (mFoodType == parent) {
			ArrayAdapter<Grade> adapter = new ArrayAdapter<Grade>(this,
					android.R.layout.simple_spinner_item, new Grade[0]);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			mGrade.setAdapter(adapter);
		}
	}

	@SuppressLint("NewApi")
	public class MultiChoiceModeListener implements GridView.MultiChoiceModeListener {
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			mode.setTitle("选中项目");
			mActionMode = mode;
			return true;
		}

		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return true;
		}

		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			return true;
		}

		public void onDestroyActionMode(ActionMode mode) {
			mAddAndExport.setVisibility(View.VISIBLE);
			mGroupReport.setVisibility(View.GONE);
			mActionMode = null;
		}

		public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
				boolean checked) {
			int selectCount = getListView().getCheckedItemCount();
			mAddAndExport.setVisibility(View.GONE);
			mGroupReport.setVisibility(View.VISIBLE);
			mode.setSubtitle(String.format("%d项", selectCount));
		}

	}
}
